package mysql

import (
	"database/sql"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"time"
)

var DB *gorm.DB
var sqlDB *sql.DB

func InitDatabase() (err error) {
	dsn := "chihiro_rw:c45D59YardD1a2w=@tcp(mysqlapmengine.service.yctxy:3306)/chihiro?charset=utf8mb4&parseTime=true&loc=Local"
	//dsn := "root:Ba9cUk@2&8@tcp(192.168.87.59:5009)/chihiro?charset=utf8mb4&parseTime=true&loc=Local"
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, //表名是否结尾加s
		},
	})
	if err != nil {
		fmt.Printf("数据库链接出错：%v\n", err)
		return
	}
	//获取获取通用数据库对象 *sql.DB
	sqlDB, err = DB.DB()
	if err != nil {
		fmt.Printf("数据库对象获取出错：%v\n", err)
		return
	}

	//验证数据库是否建立连接,出问题返回error对象，没出问题返回nil
	if err = sqlDB.Ping(); err != nil {
		fmt.Printf("数据库链接Ping测试出错：%v\n", err)
		return
	}
	sqlDB.SetConnMaxLifetime(4 * time.Hour)
	sqlDB.SetMaxOpenConns(10)
	sqlDB.SetMaxIdleConns(2)
	return

}

func CloseLinkedDatabase() {
	sqlDB.Close()
}
